import React, { Component } from 'react';

import './App.css';

import { isEmpty ,ajax,currentUser} from './common';

import { LocaleProvider, BackTop, Layout, Menu, Dropdown, Avatar, Icon, Spin } from 'antd';

import zh_CN from 'antd/lib/locale-provider/zh_CN';

import 'moment/locale/zh-cn';

import MemoryRouter from 'react-router/MemoryRouter';

import { Route, Switch, withRouter } from 'react-router';

import UIIcon from './uicomponents/UIIcon';

import DefaultDomainPage from './DefaultDomainPage';

import AppLoginPage from './loginPage';

import pageRouteMap from './AppRouteData';

import moment from 'moment';

moment.locale('zh-cn');

const Header = Layout.Header;
const Sider = Layout.Sider;
const Footer = Layout.Footer;
const Content = Layout.Content;

const SubMenu = Menu.SubMenu;

class UserAppDomains extends Component {
  state = {
    appDomains: this.props.appDomains,
    openKeys: [],
    model: 'inline',
    module: null
  };

  componentDidMount() {
    this.appDomainKeys = this.state.appDomains.map(appDomain => (
      "Domain-" + appDomain.id
    ));
    this.state.openKeys.push(this.appDomainKeys[0]);
    setTimeout(() => {
      this.props.onDomainChanged(this.state.appDomains[0]);
    });
  }

  onOpenChange = (openKeys) => {
    
    if (this.state.model === 'inline') {
      const latestOpenKey = openKeys.find(key => this.state.openKeys.indexOf(key) === -1);
      if (this.appDomainKeys.indexOf(latestOpenKey) === -1) {
        this.setState({ openKeys });
      }
      else {
        this.props.onDomainChanged(this.state.appDomains[this.appDomainKeys.indexOf(latestOpenKey)]);
        this.setState({
          openKeys: latestOpenKey ? [latestOpenKey] : [],
        });
      }
    }
  }

  onMenuItemClick = (menuItem) => {
    //console.log(menuItem);
    this.setState({ module: menuItem.item.props.module });
    //console.log(menuItem.item.props.module.path);
    this.props.onModuleChange(menuItem);
  }

  getSubMenuOrItem = (menuItem) => {
    var owner = this;
    if (menuItem && menuItem.subItems && menuItem.subItems.length > 0) {
      return (
        <SubMenu key={menuItem.menuId} title={<span><UIIcon icon={menuItem.icon} /><span>{menuItem.label}</span></span>}>
          {menuItem.subItems.map(menuItem => (
            owner.getSubMenuOrItem(menuItem)
          ))}
        </SubMenu>
      );
    }
    else {
      return (
        <Menu.Item key={menuItem.menuId} module={menuItem}>
          <UIIcon icon={menuItem.icon} />
          {menuItem.label}
        </Menu.Item>
      );
    }
  }

  render() {
    return (
      <Menu theme="dark" mode={this.state.model} inlineCollapsed="true" openKeys={this.state.openKeys} onClick={this.onMenuItemClick} onOpenChange={this.onOpenChange}>
        {this.state.appDomains.map(appDomain => (
          <SubMenu key={'Domain-' + appDomain.id} title={<span><UIIcon icon={appDomain.icon} /><span>{appDomain.shortName}</span></span>}>
            {appDomain.menuItems.map(menuItem => (
              this.getSubMenuOrItem(menuItem)
            ))}
          </SubMenu>
        ))}
      </Menu>
    );
  }
}

class PagePanelRouter extends React.PureComponent {

  goto = (path, param, cb) => {
    const { history } = this.props;
    history.push(path, param);
    if (cb) {
      setTimeout(function () { cb(); });
    }
  }

  render() {

    const { contentMap, location } = this.props;
    const pathSnippets = location ? location.pathname.split('/').filter(i => i) : [];

    if (contentMap && contentMap['/'] && pathSnippets.length === 0) {
      pathSnippets.push('');
    }

    return (
      <React.Fragment >
        {this.props.children}
      </React.Fragment>
    );
  }
}

const PagePanelWithRouter = withRouter(PagePanelRouter);


/**
 * 系统应用
 */
class App extends Component {

  state = {
    collapsed: false,
    currentUser: null,
    currentModule: null,
    appDomains : [],
    appConfig : null,
    loading: false,
    breadcrumbRouter: null,
  };

  componentDidMount(){
    this.updateUserInfo();
  }

  updateUserInfo = () => {
    ajax('SYSTEM/auth/getLoginInfo', {},  (data) => {
      //console.log(data);
      if(data !== null || data !== undefined){
        const userInfo = {
          userAccount : data.userAccount,
          userId : data.userId,
          userName : data.userName,
          userPhoto : data.userPhoto,
          userRoleIds : data.userRoleIds,
        };
        currentUser.userId =   data.userId; 
        this.setState({currentUser : userInfo,appConfig : data.appConfigMap,appDomains : data.appDomains});
      }
      else{
        this.setState({currentUser : null,appConfig : null,appDomains : []});
      }
    });
  }

  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }

  onMenuClick = (menu) => {
    //console.log(menu);
    const {currentUser} = this.state;
    if(menu.key === 'logout'){
      this.setState({currentUser : null,appConfig : null,appDomains : []});
    }
    else if(menu.key === 'userProfile'){
      this.setState({currentModule : {label : '个人中心',icon : 'user'}});
      setTimeout(() => {
        this.pageRouter.goto('/UserProfile');
      });
    }
  }

  handleModuleChange = (item) => {

    this.setState({ currentModule: item.item.props.module });
    //console.log(item.item.props.module.path);
    if (isEmpty(item.item.props.module.path) === false) {
      this.pageRouter.goto('/' + item.item.props.module.path,item.item.props.module);
    }
  }

  handleDomainChange = (domain) => {
    if(isEmpty(domain.page)){
      this.pageRouter.goto('/openDomianDefaultPage' ,domain);
    }
  }

  doLogin = (data) => {
    //console.log(data);
    const userInfo = {
      userAccount : data.result.userAccount,
      userId : data.result.userId,
      userName : data.result.userName,
      userPhoto : data.result.userPhoto,
      userRoleIds : data.result.userRoleIds,
    };

    this.setState({currentUser : userInfo,appConfig : data.result.appConfigMap,appDomains : data.result.appDomains});
  }


  render() {

    const {currentUser,appConfig,appDomains} = this.state;

    if(currentUser === null || appConfig === null || currentUser === undefined || appConfig === undefined){

      return (<AppLoginPage onLogin={this.doLogin}/>);

    }
    else{
      const menu = (
        <Menu className="menu" selectedKeys={[]} onClick={this.onMenuClick}>
          <Menu.Item key="userProfile"><Icon type="user" />个人中心</Menu.Item>
          <Menu.Item disabled><Icon type="setting" />设置</Menu.Item>
          <Menu.Item key="triggerError"><Icon type="close-circle" />触发报错</Menu.Item>
          <Menu.Divider />
          <Menu.Item key="logout"><Icon type="logout" />退出登录</Menu.Item>
        </Menu>
      );

      const routeList = [];
  
      routeList.push(
        <Route key="ShowDomainPage" exact path="/openDomianDefaultPage" render={(props) => {return ( <DefaultDomainPage pageRouter={this.pageRouter} {...props}/>)}} />
      );

      if (pageRouteMap) {
        for (const key of Object.keys(pageRouteMap)) {
          const routeItem = pageRouteMap[key];
          const { getComponent } = routeItem;
          routeList.push(
            <Route key={key} exact path={key} render={(props) => (getComponent(this, props))} />
          );
        }
      }
  
      return (
        <LocaleProvider locale={zh_CN}>
          <Layout>
            <Sider trigger={null} breakpoint="lg" collapsible collapsed={this.state.collapsed}>
              <div className="logo" key="logo">
                <h1><span><UIIcon icon={appConfig.appIcon} /></span></h1>
                <h1><span>{appConfig.appName}</span></h1>
              </div>
              <UserAppDomains appDomains={appDomains} onModuleChange={this.handleModuleChange} onDomainChanged={this.handleDomainChange} />
            </Sider>
            <Layout>
              <Header style={{ padding: 0 }}>
                <div className="globHeader">
                  <Icon className="trigger" type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'} onClick={this.toggle} />
                  <div className="right">
                    <Dropdown overlay={menu}>
                      <span className="action account">
                        <Avatar size="small" className="avatar" src={currentUser.userPhoto} />
                        <span className="name">{currentUser.userName}</span>
                      </span>
                    </Dropdown>
                  </div>
                </div>
                <div align="center">
                  <Spin size="large" spinning={this.state.loading} />
                </div>
              </Header>
              <Content style={{ margin: '10px' }}>
                <MemoryRouter>
                  <PagePanelWithRouter wrappedComponentRef={(inst) => this.pageRouter = inst} contentMap={pageRouteMap}>
                    <Switch>
                      {routeList}
                    </Switch>
                  </PagePanelWithRouter>
                </MemoryRouter>
              </Content>
              <Footer style={{ textAlign: 'center', padding: 0 }}>
                {appConfig.appDesc}
              </Footer>
              <BackTop />
            </Layout>
          </Layout>
        </LocaleProvider>
      );
    }
  }
}

export default App;